package easycloud.ecs.agent.service;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;

import easycloud.ecs.common.domain.Item;
import easycloud.ecs.common.domain.Provider;
import easycloud.ecs.common.domain.Sync;
import easycloud.ecs.common.service.ItemService;

@Service
public class ItemMetaService {

	@Inject
	private ItemService itemService;

	public Item getItem(File file, Provider provider) {
		Sync sync = null;
		for (Sync s : provider.getSyncs()) {
			if (FilenameUtils
					.wildcardMatch(file.getAbsolutePath(), s.getPath())) {
				sync = s;
				break;
			}
		}
		Item item = null;
		if (sync != null) {
			String path = file.getAbsolutePath();
			path = path
					.replaceFirst(sync.getPath(), sync.getFolder().getName());
			item = itemService.getItem(path, provider);
		}
		return item;
	}

	public Map<File, Item> getItems(Collection<File> files, Provider provider) {
		Map<File, Item> result = new HashMap<File, Item>();
		for (File file : files) {
			Item item = getItem(file, provider);
			result.put(file, item);
		}
		return result;
	}

}
